package drp.snowbell.io;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

import drp.snowbell.part.SolidTree;
import drp.snowbell.storage.IStorage;
import drp.snowbell.storage.StorageManager;


/**
 * 数据库资源
 * 
 * @author jimmy
 * 
 */
public class DbResource implements IResource {

	private URI uri;
	private Resource resource;

	public DbResource(Resource resource) {
		this.resource = resource;
	}

	public DbResource(URI uri) {
		this.uri = uri;
	}

	@Override
	public URI getURI() {
		return uri;
	}

	@Override
	public String getName() {
		return resource.getName();
	}

	@Override
	public InputStream openInputStream() {
		ByteArrayInputStream in = null;
		if (!isDirectory()) {
			String text = resource.getText();
			if (text == null) {
				text = "";
			}
			in = new ByteArrayInputStream(text.getBytes());
		}
		return in;
	}

	@Override
	public OutputStream openOutStream() {
		OutputStream out = null;
		if (!isDirectory()) {
			out = new DbOutputStream(resource);
		}
		return out;
	}

	@Override
	public boolean rename(String newName) {
		IStorage<Resource> storage = StorageManager.getCurrentStorage(Resource.class);
		SolidTree stree = (SolidTree) resource.getSkill(SolidTree.SKILL_NAME);
		Resource res = getDbResourceList(stree.getLayer(), newName);
		if (res != null) {
			// 说明新的名字已经存在
			// delete
			// storage.delete(res.getId());
			return false;
		}
		resource.setName(newName);
		return storage.save(resource) != null;
	}

	public static Resource getDbResourceList(String layer, String name) {
		IStorage<Resource> storage = StorageManager.getCurrentStorage(Resource.class);
		SkillDna sd = SkillManager.getSkillDna(Resource.ENTITY_NAME, SolidTree.SKILL_NAME);
		Property layerProp = sd.getProperty(SolidTree.PROP_LEVEL);
		Property nameProp = Farm.getDna(Resource.class).getNameProperty();
		IExp expLayer = ExpUtil.getPvEqExp(layerProp, layer);
		IExp expName = ExpUtil.getPvEqExp(nameProp, name);
		IExp where = ExpUtil.getLogicAndExp(expLayer, expName);
		List<Resource> list = storage.getList(where);
		Resource ret = null;
		if (list.size() == 1) {
			ret = list.get(0);
		} else if (list.size() > 1) {
			throw new DataOverlapedException("resource data overlaped");
		}
		return ret;
	}

	@Override
	public boolean delete() {
		IStorage<Resource> storage = StorageManager.getCurrentStorage(Resource.class);
		storage.delete(resource.getId());
		resource.setId(null);
		return true;
	}

	@Override
	public String getPath() {
		return resource.getPath();
	}

}
